package com.sky.service.impl;

import com.fasterxml.jackson.databind.ser.Serializers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;

import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.SHA256Util;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.codec.digest.DigestUtils;

import java.awt.event.WindowFocusListener;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //md5加密后匹配
        //String mpassword = DigestUtils.md5DigestAsHex(password.getBytes());

        System.out.println("H265+加盐加密后输入的密码："+SHA256Util.encryptPassword(password));
        System.out.println("存储的密码："+employee.getPassword());
        //TODO SHA256解密
        if (!SHA256Util.verifyPassword(password,employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        System.out.println("service当前线程id：" + Thread.currentThread().getId());
        Employee employee = new Employee();
        //spring的beanutils类对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //默认正常状态
        employee.setStatus(StatusConstant.ENABLE);
        //使用md5加盐加密，默认密码123456
        //employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        // 生成sha256码
        String sha256Hex = SHA256Util.encryptPassword(PasswordConstant.DEFAULT_PASSWORD);

        //设置密码
        employee.setPassword(sha256Hex);

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //设置当前记录创建人id和修改人id
        //从ThreadLocal中取出信息
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //其实就是select * from employee limit 0,10
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //返回结果是page类型的，取出属性构造PageResult对象返回即可
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        long total = page.getTotal();
        List records = page.getResult();

        return new PageResult(total, records);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        // update employee set status = ? where id = ?
//        Employee employee = new Employee();
//        employee.setId(id);
//        employee.setStatus(status);
        //利用builder构造器创建对象
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();

        employeeMapper.update(employee);
    }

    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        //对密码进行脱敏
        employee.setPassword("****");
        return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        employee.setUpdateTime(LocalDateTime.now());
        //拦截器中已经将用户id（empId）作为属性set到BaseContext这个ThreadLocal对象中了
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }

    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        Long id = BaseContext.getCurrentId();
        System.out.println("老密码："+passwordEditDTO.getOldPassword());
        System.out.println("新密码："+passwordEditDTO.getNewPassword());
//        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
//        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());

        //SHA256加密
        String oldPassword = SHA256Util.encryptPassword(passwordEditDTO.getOldPassword());
        String newPassword = SHA256Util.encryptPassword(passwordEditDTO.getNewPassword());

        //存入加密的密码
        Employee employee = employeeMapper.getById(id);
        System.out.println("老密码加密："+oldPassword);
        System.out.println("匹配到用户的密码："+employee.getPassword());

        if (!oldPassword.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        else if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        else {
            employee.setPassword(newPassword);
            employee.setUpdateUser(id);
            employee.setUpdateTime(LocalDateTime.now());
            employeeMapper.update(employee);
        }

    }

    @Override
    public void logout() {
        BaseContext.removeCurrentId();
    }


}
